import 'dart:async';
import 'package:flutter/material.dart';
import 'package:video_player/video_player.dart';
import 'package:chewie/chewie.dart';
import 'package:native_video_cache/native_video_cache.dart';
import '../utils/error_handler.dart';

/// 播放器状态枚举
enum NativeAvPlayerState {
  idle,
  loading,
  ready,
  playing,
  paused,
  buffering,
  error,
  disposed,
}

/// 播放器事件回调
typedef PlayerEventCallback = void Function(NativeAvPlayerState state);
typedef PlayerProgressCallback = void Function(
    Duration position, Duration duration);
typedef PlayerErrorCallback = void Function(String error);
typedef CacheProgressCallback = void Function(double progress);
typedef CacheStatusCallback = void Function(CacheStatus status);

/// 自定义视频播放器控制器
class NativeAvPlayerController extends ChangeNotifier {
  VideoPlayerController? _videoPlayerController;
  ChewieController? _chewieController;

  String? _currentUrl;
  String? _proxyUrl;
  bool _isInitialized = false;
  bool _isDisposed = false;
  NativeAvPlayerState _state = NativeAvPlayerState.idle;
  String? _errorMessage;
  VideoErrorInfo? _currentErrorInfo;

  // 缓存相关状态
  double _cacheProgress = 0.0;
  CacheStatus _cacheStatus = CacheStatus.none;

  // 播放器配置
  bool _autoPlay = false;
  bool _looping = false;
  bool _allowFullScreen = true;
  bool _showControls = true;
  double _aspectRatio = 16 / 9;

  // 事件回调
  PlayerEventCallback? onStateChanged;
  PlayerProgressCallback? onProgressChanged;
  PlayerErrorCallback? onError;

  // 缓存回调
  CacheProgressCallback? onCacheProgressChanged;
  CacheStatusCallback? onCacheStatusChanged;

  // 缓存监听器引用（用于dispose时移除）
  CacheProgressListener? _cacheProgressListener;
  CacheStatusListener? _cacheStatusListener;
  CacheErrorListener? _cacheErrorListener;

  // 错误去重相关
  String? _lastErrorMessage;
  DateTime? _lastErrorTime;

  // Getters
  VideoPlayerController? get videoPlayerController => _videoPlayerController;
  ChewieController? get chewieController => _chewieController;
  String? get currentUrl => _currentUrl;
  String? get proxyUrl => _proxyUrl;
  bool get isInitialized => _isInitialized;
  NativeAvPlayerState get state => _state;
  String? get errorMessage => _errorMessage;
  VideoErrorInfo? get currentErrorInfo => _currentErrorInfo;
  bool get isPlaying => _videoPlayerController?.value.isPlaying ?? false;
  bool get isBuffering => _videoPlayerController?.value.isBuffering ?? false;
  Duration get position =>
      _videoPlayerController?.value.position ?? Duration.zero;
  Duration get duration =>
      _videoPlayerController?.value.duration ?? Duration.zero;
  double get aspectRatio =>
      _videoPlayerController?.value.aspectRatio ?? _aspectRatio;

  // 全屏状态检测（使用chewie的）
  bool get isFullScreen => _chewieController?.isFullScreen ?? false;

  // 缓存状态
  double get cacheProgress => _cacheProgress;
  CacheStatus get cacheStatus => _cacheStatus;

  // 配置设置
  bool get autoPlay => _autoPlay;
  bool get looping => _looping;
  bool get allowFullScreen => _allowFullScreen;
  bool get showControls => _showControls;

  set autoPlay(bool value) {
    _autoPlay = value;
    _updateChewieController();
  }

  set looping(bool value) {
    _looping = value;
    _updateChewieController();
  }

  set allowFullScreen(bool value) {
    _allowFullScreen = value;
    _updateChewieController();
  }

  set showControls(bool value) {
    _showControls = value;
    _updateChewieController();
  }

  /// 初始化播放器
  Future<void> initialize(
    String url, {
    bool autoPlay = false,
    bool looping = false,
    bool allowFullScreen = true,
    bool showControls = true,
    double? aspectRatio,
  }) async {
    if (_isDisposed) return;

    try {
      _setState(NativeAvPlayerState.loading);

      _currentUrl = url;
      _autoPlay = autoPlay;
      _looping = looping;
      _allowFullScreen = allowFullScreen;
      _showControls = showControls;
      if (aspectRatio != null) _aspectRatio = aspectRatio;

      // 设置缓存监听器
      _setupCacheListeners();

      // 获取代理URL（与缓存系统集成）
      _proxyUrl = await NativeVideoCacheManager.getProxyUrl(url);

      // 主动启动缓存（边播边缓存）
      // 注意：必须调用startCache才能真正触发缓存下载
      try {
        await NativeVideoCacheManager.startCache(url);
        debugPrint('NativeAvPlayerController: 缓存启动成功');
      } catch (e) {
        debugPrint('NativeAvPlayerController: 缓存启动失败，但继续播放: $e');
      }

      // 创建VideoPlayerController
      _videoPlayerController =
          VideoPlayerController.networkUrl(Uri.parse(_proxyUrl!));

      // 添加监听器
      _videoPlayerController!.addListener(_onVideoPlayerStateChanged);

      // 初始化播放器
      await _videoPlayerController!.initialize();

      // 创建ChewieController
      _createChewieController();

      _isInitialized = true;
      _setState(NativeAvPlayerState.ready);

      // 自动播放
      if (_autoPlay) {
        await play();
      }
    } catch (e) {
      // 只处理非VideoPlayer相关的错误（如网络请求、缓存启动等）
      // VideoPlayer的错误会通过_onVideoPlayerStateChanged统一处理
      debugPrint('NativeAvPlayerController: 初始化过程中出现非播放器错误 - $e');

      // 如果是在创建VideoPlayerController之前的错误，直接处理
      if (_videoPlayerController == null) {
        _handleError(e.toString());
      }
      // 如果VideoPlayerController已创建，其错误会通过监听器处理，这里不重复处理
    }
  }

  /// 设置缓存监听器
  void _setupCacheListeners() {
    if (_currentUrl == null) return;

    // 创建监听器实例并保存引用
    _cacheProgressListener = (String url, double progress) {
      if (!_isDisposed && url == _currentUrl) {
        _cacheProgress = progress;
        onCacheProgressChanged?.call(progress);
        notifyListeners();
      }
    };

    _cacheStatusListener = (String url, CacheStatus status) {
      if (!_isDisposed && url == _currentUrl) {
        _cacheStatus = status;
        onCacheStatusChanged?.call(status);
        notifyListeners();
      }
    };

    _cacheErrorListener = (String url, String error) {
      if (!_isDisposed && url == _currentUrl) {
        debugPrint('NativeAvPlayerController: 缓存错误 - $error');
      }
    };

    // 添加监听器
    NativeVideoCacheManager.addProgressListener(_cacheProgressListener!);
    NativeVideoCacheManager.addStatusListener(_cacheStatusListener!);
    NativeVideoCacheManager.addErrorListener(_cacheErrorListener!);
  }

  /// 创建Chewie控制器
  void _createChewieController() {
    if (_videoPlayerController == null) return;

    _chewieController?.dispose();
    _chewieController = ChewieController(
      videoPlayerController: _videoPlayerController!,
      autoPlay: _autoPlay,
      looping: _looping,
      allowFullScreen: _allowFullScreen,
      showControls: _showControls,
      aspectRatio: _aspectRatio,
      placeholder: Container(
        color: Colors.black,
        child: const Center(
          child: CircularProgressIndicator(),
        ),
      ),
      errorBuilder: (context, errorMessage) {
        return _buildErrorWidget();
      },
    );
  }

  /// 构建错误显示Widget
  Widget _buildErrorWidget() {
    if (_currentErrorInfo == null) {
      return Container(
        color: Colors.black,
        child: const Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Icon(
                Icons.error,
                color: Colors.red,
                size: 48,
              ),
              SizedBox(height: 16),
              Text(
                '视频加载中...',
                style: TextStyle(color: Colors.white),
                textAlign: TextAlign.center,
              ),
            ],
          ),
        ),
      );
    }

    final errorInfo = _currentErrorInfo!;

    return Container(
      color: Colors.black,
      padding: const EdgeInsets.all(20),
      child: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            // 错误图标
            Text(
              errorInfo.icon,
              style: const TextStyle(fontSize: 48),
            ),
            const SizedBox(height: 16),

            // 错误标题
            Text(
              errorInfo.title,
              style: const TextStyle(
                color: Colors.white,
                fontSize: 18,
                fontWeight: FontWeight.bold,
              ),
              textAlign: TextAlign.center,
            ),
            const SizedBox(height: 8),

            // 错误描述
            Text(
              errorInfo.message,
              style: const TextStyle(
                color: Colors.white70,
                fontSize: 14,
              ),
              textAlign: TextAlign.center,
            ),
            const SizedBox(height: 16),

            // 解决建议
            if (errorInfo.suggestions.isNotEmpty) ...[
              const Text(
                '解决建议:',
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 14,
                  fontWeight: FontWeight.bold,
                ),
              ),
              const SizedBox(height: 8),
              ...errorInfo.suggestions.map(
                (suggestion) => Padding(
                  padding: const EdgeInsets.symmetric(vertical: 2),
                  child: Row(
                    children: [
                      const Text(
                        '• ',
                        style: TextStyle(color: Colors.white70),
                      ),
                      Expanded(
                        child: Text(
                          suggestion,
                          style: const TextStyle(
                            color: Colors.white70,
                            fontSize: 12,
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
              ),
              const SizedBox(height: 16),
            ],

            // 重试按钮
            if (errorInfo.canRetry)
              ElevatedButton.icon(
                onPressed: reload,
                icon: const Icon(Icons.refresh),
                label: const Text('重试'),
                style: ElevatedButton.styleFrom(
                  backgroundColor: Colors.blue,
                  foregroundColor: Colors.white,
                ),
              ),
          ],
        ),
      ),
    );
  }

  /// 更新Chewie控制器
  void _updateChewieController() {
    if (_isInitialized && _videoPlayerController != null) {
      _createChewieController();
      notifyListeners();
    }
  }

  /// 播放
  Future<void> play() async {
    if (_videoPlayerController != null && _isInitialized) {
      await _videoPlayerController!.play();
      _setState(NativeAvPlayerState.playing);
    }
  }

  /// 暂停
  Future<void> pause() async {
    if (_videoPlayerController != null && _isInitialized) {
      await _videoPlayerController!.pause();
      _setState(NativeAvPlayerState.paused);
    }
  }

  /// 停止
  Future<void> stop() async {
    if (_videoPlayerController != null && _isInitialized) {
      await _videoPlayerController!.pause();
      await _videoPlayerController!.seekTo(Duration.zero);
      _setState(NativeAvPlayerState.ready);
    }
  }

  /// 跳转到指定位置
  Future<void> seekTo(Duration position) async {
    if (_videoPlayerController != null && _isInitialized) {
      await _videoPlayerController!.seekTo(position);
    }
  }

  /// 设置播放速率
  Future<void> setPlaybackSpeed(double speed) async {
    if (_videoPlayerController != null && _isInitialized) {
      await _videoPlayerController!.setPlaybackSpeed(speed);
    }
  }

  /// 设置音量
  Future<void> setVolume(double volume) async {
    if (_videoPlayerController != null && _isInitialized) {
      await _videoPlayerController!.setVolume(volume);
    }
  }

  /// 进入全屏
  void enterFullScreen() {
    _chewieController?.enterFullScreen();
  }

  /// 退出全屏
  void exitFullScreen() {
    _chewieController?.exitFullScreen();
  }

  /// 切换全屏状态
  void toggleFullScreen() {
    _chewieController?.toggleFullScreen();
  }

  /// 视频播放器状态监听
  void _onVideoPlayerStateChanged() {
    if (_videoPlayerController == null || _isDisposed) return;

    final value = _videoPlayerController!.value;

    // 处理错误
    if (value.hasError) {
      _handleError(value.errorDescription ?? '未知播放错误');
      return;
    }

    // 处理缓冲状态
    if (value.isBuffering) {
      _setState(NativeAvPlayerState.buffering);
    } else if (value.isPlaying) {
      _setState(NativeAvPlayerState.playing);
    } else {
      _setState(NativeAvPlayerState.paused);
    }

    // 进度回调
    onProgressChanged?.call(value.position, value.duration);
  }

  /// 设置播放器状态
  void _setState(NativeAvPlayerState newState) {
    if (_state != newState) {
      _state = newState;
      onStateChanged?.call(_state);
      notifyListeners();
    }
  }

  /// 处理错误
  void _handleError(String error) async {
    _errorMessage = error;

    // 使用智能错误分析器
    if (_currentUrl != null) {
      try {
        _currentErrorInfo =
            await VideoErrorHandler.analyzeError(error, _currentUrl!);
      } catch (e) {
        // 如果错误分析失败，使用默认错误信息
        _currentErrorInfo = VideoErrorInfo(
          title: '播放出现问题',
          message: '视频暂时无法播放',
          suggestions: ['请检查网络连接', '尝试重新播放'],
          icon: '⚠️',
          originalError: error,
          isNetworkError: false,
          canRetry: true,
        );
      }
    }

    _setState(NativeAvPlayerState.error);

    // 错误去重：使用分析后的标题进行去重，避免重复的错误回调
    final errorToReport = _currentErrorInfo?.title ?? error;
    final now = DateTime.now();

    // 如果是相同的错误且在3秒内，则不重复回调
    if (_lastErrorMessage != errorToReport ||
        _lastErrorTime == null ||
        now.difference(_lastErrorTime!) > const Duration(seconds: 3)) {
      _lastErrorMessage = errorToReport;
      _lastErrorTime = now;
      onError?.call(errorToReport);
      debugPrint('NativeAvPlayerController: 错误回调 - $errorToReport');
    } else {
      debugPrint('NativeAvPlayerController: 跳过重复错误回调 - $errorToReport');
    }

    notifyListeners(); // 确保UI更新
  }

  /// 释放资源
  @override
  void dispose() {
    if (_isDisposed) return;

    _isDisposed = true;

    // 停止当前URL的缓存任务
    if (_currentUrl != null) {
      try {
        NativeVideoCacheManager.stopCache(_currentUrl!);
        debugPrint('NativeAvPlayerController: 停止缓存任务 - $_currentUrl');
      } catch (e) {
        debugPrint('NativeAvPlayerController: 停止缓存任务失败 - $e');
      }
    }

    // 清除回调函数
    onCacheProgressChanged = null;
    onCacheStatusChanged = null;
    onProgressChanged = null;
    onStateChanged = null;
    onError = null;

    // 移除NativeVideoCacheManager监听器
    try {
      if (_cacheProgressListener != null) {
        NativeVideoCacheManager.removeProgressListener(_cacheProgressListener!);
      }
      if (_cacheStatusListener != null) {
        NativeVideoCacheManager.removeStatusListener(_cacheStatusListener!);
      }
      if (_cacheErrorListener != null) {
        NativeVideoCacheManager.removeErrorListener(_cacheErrorListener!);
      }
    } catch (e) {
      debugPrint('NativeAvPlayerController: 移除监听器失败 - $e');
    }

    _videoPlayerController?.removeListener(_onVideoPlayerStateChanged);
    _videoPlayerController?.dispose();
    _chewieController?.dispose();

    _setState(NativeAvPlayerState.disposed);

    super.dispose();
  }

  /// 重新加载
  Future<void> reload() async {
    if (_currentUrl != null) {
      // 清除之前的错误状态
      _clearError();

      // 重新初始化
      await initialize(
        _currentUrl!,
        autoPlay: _autoPlay,
        looping: _looping,
        allowFullScreen: _allowFullScreen,
        showControls: _showControls,
        aspectRatio: _aspectRatio,
      );
    }
  }

  /// 清除错误状态
  void _clearError() {
    _errorMessage = null;
    _currentErrorInfo = null;
    _lastErrorMessage = null;
    _lastErrorTime = null;
    if (_state == NativeAvPlayerState.error) {
      _setState(NativeAvPlayerState.idle);
    }
    notifyListeners();
  }
}
